import shutil
import time
import uuid

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from user_api.models import Video
from util.fileUtil import VIDEO_CHUNK_FILE_PATH, VIDEO_FILE_PATH, VIDEO_IMG_FILE_PATH
from util.request_util import post_only, login_only


@csrf_exempt
@post_only
@login_only
def get_video_upload_uuid_api(request):
    """
    获取上传视频的UUID
    """
    session = request.session
    upload_uuid = str(uuid.uuid4()).replace("-", "")
    session["upload_uuid"] = upload_uuid
    session["upload_index"] = 0
    return JsonResponse({"state": 1, "data": upload_uuid})

@csrf_exempt
@post_only
@login_only
def upload_video_chunk_api(request):
    """
    切片上传视频
    """
    session = request.session
    formData = request.POST
    upload_uuid = formData.get('uuid')

    video = Video.objects.filter(video_uuid=upload_uuid).first()
    if video:
        return JsonResponse({'state': -4, 'message': '视频已上传'})

    if session.get('upload_uuid') != formData.get('uuid'):
        return JsonResponse({'state': -1})

    chunkIndex = formData.get('chunkIndex')

    if str(session.get('upload_index')) != chunkIndex:
        if chunkIndex == '0':
            session['upload_index'] = 0
        else:
            totalChunks = formData.get('totalChunks')
            if totalChunks == str(session["upload_index"]):
                return JsonResponse({'state': 2})
            return JsonResponse({'state': -1})

    video_chunk_path = VIDEO_CHUNK_FILE_PATH / upload_uuid

    if not video_chunk_path.exists():
        video_chunk_path.mkdir(exist_ok=True, parents=True)

    chunk = request.FILES.get('chunk')
    file_path = video_chunk_path / (upload_uuid + chunkIndex)

    with open(file_path, "wb") as f:
        f.write(chunk.read())

    session["upload_index"] = session["upload_index"] + 1

    return JsonResponse({'state': 1})

@csrf_exempt
@post_only
@login_only
def upload_video_info_api(request):
    """
    上传视频信息
    """
    session = request.session
    formData = request.POST
    upload_uuid = formData.get('uuid')
    video_chunk_path = VIDEO_CHUNK_FILE_PATH / upload_uuid
    # uuid不匹配
    if session.get('upload_uuid') != formData.get('uuid'):
        return JsonResponse({'state': -3})
    # 检查区块数量是否匹配
    totalChunks = formData.get('totalChunks')
    if totalChunks != str(session["upload_index"]):
        return JsonResponse({'state': -2, 'index': session["upload_index"]})
    # 获取到所有的切片
    chunk_list = [video_chunk_path / f"{upload_uuid}{i}" for i in range(session["upload_index"])]

    # 合并切片
    merged_file_path = VIDEO_FILE_PATH / f"{upload_uuid}_merged.mp4"
    with open(merged_file_path, 'ab') as merged_file:
        for index, chunk_path in enumerate(chunk_list):
            if not chunk_path.exists():
                session["upload_index"] = index
                return JsonResponse({'state': -1, 'index': index})
            with open(chunk_path, 'rb') as chunk_file:
                merged_file.write(chunk_file.read())

    # todo: 检查视频类型

    # 从表单拿信息
    video_title = formData.get("title")
    video_desc = formData.get("desc")
    video_img = request.FILES.get('img')
    # 存储图片
    video_img_path = VIDEO_IMG_FILE_PATH / (upload_uuid + ".png")
    with open(video_img_path, "wb") as f:
        f.write(video_img.read())

    # todo: 检查图片类型

    # 数据库存信息
    video = Video.objects.filter(video_uuid=upload_uuid).first()
    if video:
        return JsonResponse({'state': -4, 'message': '视频已上传'})

    Video.objects.create(video_uuid=upload_uuid, user_id=session["id"], video_title=video_title, video_desc=video_desc)

    # 删除切片
    while True:
        try:
            shutil.rmtree(video_chunk_path)
            break
        except:
            time.sleep(0.1)

    return JsonResponse({'state': 1})
